package com.jereh.topnews.activity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.Switch;

import com.jereh.topnews.R;

public class SettingActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener{

    private Switch listShow,notice,favotshare;
    private SharedPreferences sp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        listShow=(Switch)findViewById(R.id.listShow);
        notice=(Switch)findViewById(R.id.notice);
        favotshare=(Switch)findViewById(R.id.favotshare);
        sp=getSharedPreferences("my_setting",MODE_PRIVATE);
        listShow.setOnCheckedChangeListener(this);
        notice.setOnCheckedChangeListener(this);
        favotshare.setOnCheckedChangeListener(this);
        initStatus();
    }

    private void initStatus(){
        if(sp.getBoolean("first_setting",true)) {
            SharedPreferences.Editor editor=sp.edit();
            editor.putBoolean("first_setting",false);
            editor.commit();
            setChange(listShow);
            setChange(notice);
            setChange(favotshare);
        } else {
            getChange(listShow);
            getChange(notice);
            getChange(favotshare);
        }

    }

    private void getChange(CompoundButton btn){
        btn.setChecked(sp.getBoolean(btn.getTag().toString(),true));
    }

    private void setChange(CompoundButton btn){
        SharedPreferences.Editor editor=sp.edit();
        editor.putBoolean(btn.getTag().toString(),btn.isChecked());
        editor.commit();
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        setChange(buttonView);
    }
}
